package com.shengqi.xinnongren.work.ui.user.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.utils.BitmapHelper;
import com.shengqi.xinnongren.common.utils.ImageUtils;
import com.shengqi.xinnongren.common.utils.LogUtil;
import com.shengqi.xinnongren.common.utils.RxGalleryMyApi;
import com.shengqi.xinnongren.common.utils.SimpleRxGalleryFinal;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.common.utils.ToastUtils;
import com.shengqi.xinnongren.work.ui.user.model.RefundBean;
import com.shengqi.xinnongren.work.ui.user.model.UploadPicBean;
import com.shengqi.xinnongren.work.ui.user.presenter.ApplyRefundPresenter;
import com.shengqi.xinnongren.work.ui.user.view.ApplyRefundView;
import com.yalantis.ucrop.util.FileUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultDisposable;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import cn.finalteam.rxgalleryfinal.ui.base.IRadioImageCheckedListener;

/**
 * 申请退款
 */
public class ApplyRefundActivity extends BaseMvpActivity<ApplyRefundView, ApplyRefundPresenter> implements ApplyRefundView {

    private static final String EXTRA_ORDER_ID = "order_id";

    @BindView(R.id.rv_reason)
    RecyclerView mRvReason;
    @BindView(R.id.rv_goods)
    RecyclerView mRvGoods;
    @BindView(R.id.rv_pic)
    RecyclerView mRvPic;

    @BindView(R.id.ll_refund_tips)
    LinearLayout mLlRefundTips;

    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.et_reason)
    EditText edt_reason;

    private String mOrderId;

    private PicAdapter mAdapter;
    private List<String> mPicList;
    private List<String> mPicSaveList;

    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, ApplyRefundActivity.class);
        intent.putExtra(EXTRA_ORDER_ID, orderId);
        context.startActivity(intent);
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_apply_refund;
    }

    @Override
    protected void initView() {
        mOrderId = getIntent().getStringExtra(EXTRA_ORDER_ID);

        mPicSaveList = new ArrayList<>();
        mPicList = new ArrayList<>();
        mAdapter = new PicAdapter(this, mPicList);
        mRvPic.setAdapter(mAdapter);
        mRvPic.setLayoutManager(new GridLayoutManager(this, 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        mPresenter.getData(mOrderId);
    }

    @OnClick(R.id.iv_close_tips)
    void iv_close_tips() {
        mLlRefundTips.setVisibility(View.GONE);
//        startActivity(new Intent(this, RefundDetailsActivity.class));
    }

    @OnClick(R.id.ll_photo)
    void ll_photo() {
        if (mPicList.size() < 3) {
            chooseFromAlbum();
        } else
            ToastHelper.getInstance(this).showWarn("最多选择三张照片");
    }

    @OnClick(R.id.tv_commit)
    void tv_commit() {
        boolean hasSelect = false;
        String comId = "";
        for (RefundBean.ComListBean comListBean : mList) {
            if (comListBean.isSelect()) {
                hasSelect = true;
                comId += comListBean.getComId() + ",";
            }
        }
        if (!hasSelect) {
            ToastHelper.getInstance(this).showWarn("请选择退货商品");
            return;
        }
        comId = comId.substring(0, comId.length() - 1);
        String reason = edt_reason.getText().toString();
        if (TextUtils.isEmpty(reason)) {
            ToastHelper.getInstance(this).showWarn("请选择或输入退款原因");
            return;
        }
        String pic = "";
        for (String path : mPicSaveList) {
            pic += path + ",";
        }
        if (!TextUtils.isEmpty(pic))
            pic = pic.substring(0, pic.length() - 1);
        mPresenter.commitRefundInfo(mOrderId, getCommitJsonArray(), reason, pic);

    }


    @Override
    protected ApplyRefundPresenter createPresenter() {
        return new ApplyRefundPresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
    }

    @Override
    public void showRequestFailed(String message) {
        ToastHelper.getInstance(this).showWarn(message);
    }

    /**
     * 数据回调
     *
     * @param bean
     */
    @Override
    public void showRefundRes(RefundBean bean) {
        setGoodsList(bean.getComList());
        setReasonList(bean.getReturnReason());
    }

    @Override
    public void showCalculateRes(String money) {
        mTvMoney.setText(String.format("%s元", money));
    }


    private List<RefundBean.ComListBean> mList = new ArrayList<>();

    private void setGoodsList(List<RefundBean.ComListBean> comList) {
        mList.clear();
        mList.addAll(comList);
        for (RefundBean.ComListBean comListBean : comList) {
            for (RefundBean.ComListBean.SkuListBean skuListBean : comListBean.getSkuList()) {
                skuListBean.setShopCarNum(skuListBean.getShopCarNum());
            }
        }

        mRvGoods.setAdapter(new GoodsAdapter(R.layout.item_refund_goods, comList));
        mRvGoods.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        DividerItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider));
        mRvGoods.addItemDecoration(itemDecoration);
    }

    private void setReasonList(List<String> reason) {
        mRvReason.setAdapter(new ReasonAdapter(R.layout.item_reason, reason));
        mRvReason.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
    }

    /**
     * 勾选算钱
     */
    private void calculateMoney() {
        mPresenter.calculateMoney(mOrderId, getCommitJsonArray());
    }

    /**
     * 获取结算 提交所需参数格式
     *
     * @return
     */
    @NonNull
    private JSONArray getCommitJsonArray() {
        JSONArray jsonArray = new JSONArray();
        for (RefundBean.ComListBean comListBean : mList) {
            if (comListBean.isSelect()) {
                for (RefundBean.ComListBean.SkuListBean skuListBean : comListBean.getSkuList()) {
                    try {
                        JSONObject object = new JSONObject();
                        object.put("skuId", skuListBean.getSkuId());
                        object.put("shopCarNum", skuListBean.getShopCarNum());
                        jsonArray.put(object);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return jsonArray;
    }


    class PicAdapter extends RecyclerView.Adapter<PicAdapter.Holder> {

        private Context mContext;
        private List<String> mPicList;

        public PicAdapter(Context context, List<String> picList) {
            mContext = context;
            mPicList = picList;
        }

        @NonNull
        @Override
        public PicAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            PicAdapter.Holder holder = new PicAdapter.Holder(getLayoutInflater().inflate(R.layout.item_choose_pic, parent, false));
            holder.ivPic.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ViewGroup.LayoutParams layoutParams = holder.ivPic.getLayoutParams();
                    layoutParams.height = holder.ivPic.getWidth();
                    holder.ivPic.setLayoutParams(layoutParams);
                    holder.ivPic.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });

            holder.vReduce.setOnClickListener(v -> {
                mPicList.remove(holder.getAdapterPosition());
                mPicSaveList.remove(holder.getAdapterPosition());
                notifyDataSetChanged();
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull PicAdapter.Holder holder, int position) {
            Glide.with(mContext).load(mPicList.get(position)).into(holder.ivPic);
            holder.vReduce.setVisibility(View.VISIBLE);
        }

        @Override
        public int getItemCount() {
            return mPicList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.iv_pic)
            ImageView ivPic;
            @BindView(R.id.v_reduce)
            View vReduce;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }


    class ReasonAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public ReasonAdapter(int layoutResId, @Nullable List<String> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.tv_title, item);
            helper.itemView.setOnClickListener(v -> edt_reason.setText(edt_reason.getText().toString() + item));
        }

    }

    class GoodsAdapter extends BaseQuickAdapter<RefundBean.ComListBean, BaseViewHolder> {

        public GoodsAdapter(int layoutResId, @Nullable List<RefundBean.ComListBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, RefundBean.ComListBean item) {

            ImageView mIvMark = helper.getView(R.id.iv_mark);
            ImageView iv = helper.getView(R.id.item_pic);
            ImageUtils.showImage(ApplyRefundActivity.this, item.getPicUrl(), iv);
            helper.setText(R.id.item_title, item.getComName());

            RecyclerView recyclerView = helper.getView(R.id.rv_spec);
            recyclerView.setLayoutManager(new LinearLayoutManager(ApplyRefundActivity.this));
            recyclerView.setAdapter(new GoodsSubAdapter(R.layout.item_cart_specification, item.getSkuList(), item.isSelect()));

            mIvMark.setOnClickListener(v -> {
                item.setSelect(!item.isSelect());
                notifyDataSetChanged();
                calculateMoney();
            });
            helper.setImageResource(R.id.iv_mark, item.isSelect() ? R.mipmap.ic_check_checked : R.mipmap.ic_check_normal);
        }
    }

    class GoodsSubAdapter extends BaseQuickAdapter<RefundBean.ComListBean.SkuListBean, BaseViewHolder> {

        private boolean mIsSelect;

        public GoodsSubAdapter(int layoutResId, @Nullable List<RefundBean.ComListBean.SkuListBean> data, boolean isSelect) {
            super(layoutResId, data);
            mIsSelect = isSelect;
        }

        @Override
        protected void convert(BaseViewHolder helper, RefundBean.ComListBean.SkuListBean item) {
            helper.setText(R.id.item_price, String.format("￥%s", item.getPrice()));
            helper.setText(R.id.tv_sku_name, TextUtils.isEmpty(item.getSkuName()) ? "" : String.format("/%s", item.getSkuName()));
//            helper.setText(R.id.item_unit_price, String.format("单价：￥%s", item.getUnitPrice()));
            helper.setText(R.id.item_num, item.getShopCarNum() + "");

            //加减
            View iv_plus = helper.getView(R.id.iv_plus);
            View iv_reduce = helper.getView(R.id.iv_reduce);

            iv_plus.setOnClickListener(v -> {
                item.setShopCarNum(item.getShopCarNum() + 1 > item.localNum ? item.getShopCarNum() : item.getShopCarNum() + 1);
                notifyDataSetChanged();
                if (mIsSelect) {
                    calculateMoney();
                }
            });
            iv_reduce.setOnClickListener(v -> {
                item.setShopCarNum(item.getShopCarNum() - 1 > 0 ? item.getShopCarNum() - 1 : item.getShopCarNum());
                notifyDataSetChanged();
                if (mIsSelect) {
                    calculateMoney();
                }
            });
            if (item.getShopCarNum() >= item.localNum) {
                iv_plus.setAlpha(0.5f);
                iv_plus.setEnabled(false);
            } else {
                iv_plus.setAlpha(1f);
                iv_plus.setEnabled(true);
            }
            if (item.getShopCarNum() <= 1) {
                iv_reduce.setAlpha(0.5f);
                iv_reduce.setEnabled(false);
            } else {
                iv_reduce.setAlpha(1f);
                iv_reduce.setEnabled(true);
            }


        }
    }

    private void chooseFromAlbum() {
        RxGalleryMyApi instance =
                RxGalleryMyApi.getInstance(this);
        instance.openGalleryRadioImgDefault(new RxBusResultDisposable<ImageRadioResultEvent>() {
            @Override
            protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
                LogUtil.i("只要选择图片就会触发");
            }
        }).onCropImageResult(
                new IRadioImageCheckedListener() {
                    @Override
                    public void cropAfter(Object t) {
                        File file = (File) t;
//                        RequestOptions options = new RequestOptions();
//                        options.centerCrop();
//                        compressAndUploadHeadImg(file.getAbsolutePath());
                        doSomethingWithFile(file);
                        LogUtil.i("裁剪完成");
                    }

                    @Override
                    public boolean isActivityFinish() {
                        LogUtil.i("返回false不关闭，返回true则为关闭");
                        return true;
                    }
                });
    }

    private void takePhoto() {
        SimpleRxGalleryFinal.get().init(
                new SimpleRxGalleryFinal.RxGalleryFinalCropListener() {
                    @NonNull
                    @Override
                    public Activity getSimpleActivity() {
                        return ApplyRefundActivity.this;
                    }

                    @Override
                    public void onCropCancel() {
                        ToastUtils.showShort(getSimpleActivity(), "操作被取消");
                    }

                    @Override
                    public void onCropSuccess(@Nullable Uri uri) {
                        if (uri != null) {
                            String path = FileUtils.getPath(getSimpleActivity(), uri);
                            compressAndUploadHeadImg(path);
                        } else {
                            ToastUtils.showShort(getSimpleActivity(), "图片不存在");
                        }
                    }

                    @Override
                    public void onCropError(@NonNull String errorMessage) {
                        ToastUtils.showShort(getSimpleActivity(), errorMessage);
                    }
                }
        ).openCamera();
    }

    private void compressAndUploadHeadImg(String path) {
        File file = new File(path);
        // 压缩头像并保存
        Bitmap bitmap = BitmapHelper
                .compressImage(BitmapFactory.decodeFile(file.getAbsolutePath()));
        LogUtil.e(file.getParent());
        File PHOTO_DIR = new File(file.getParent());
        File headFile = new File(PHOTO_DIR, "head.jpg");//设置文件名称
        if (headFile.exists()) {
            headFile.delete();
        }
        try {
            headFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(headFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 上传用户头像
        LogUtil.e(headFile.getAbsolutePath());
        doSomethingWithFile(headFile);
    }

    private void doSomethingWithFile(File headFile) {
        mPresenter.updateHeadImg(headFile);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SimpleRxGalleryFinal.get().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onUploadPicSucceed(List<UploadPicBean> picBeanList) {
        if (picBeanList.size() == 0) {
            return;
        }
        mRvPic.setVisibility(View.VISIBLE);
        mPicList.add(picBeanList.get(0).viewPath);
        mPicSaveList.add(picBeanList.get(0).savePath);
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void showCommitRefundInfoRes(String message) {
        ToastHelper.getInstance(this).showSucceed(message);
        finish();
    }
}
